package com.cheng.chengrobot.service.gpt;

import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AiRequest
{


    @Autowired
    @Qualifier("proxyOkHttp")
    private OkHttpClient.Builder okHttpClientBuilder;

    @Value("${gpt.api-key}")
    private String gptApiKey;

    //请求gpt的对话接口的方法，接收给对话接口的json，返回响应的json
    public String callGpt(String json)
    {

        //构建请求对象
        OkHttpClient okHttpClient = okHttpClientBuilder.build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url("https://api.openai.com/v1/chat/completions")
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + gptApiKey)
                //                .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)")
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = null;
        try
        {
            //发送请求
            response = okHttpClient.newCall(request).execute();
            //解析响应体，取出gpt回复
//            String responseBodyString = response.body().string();
            return response.body().string();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            //关闭响应
            if (response != null) response.close();

        }



        return null;
    }
}
